// src/pages/menu/index.tsx - 菜单组件
import { useEffect, useState } from 'react';
import { Routes, Route } from 'react-router-dom';
import { Menu, MenuProps } from 'antd';
import { HomeOutlined, ToolOutlined, CalendarOutlined } from '@ant-design/icons';
// 引入页面组件
import HomePage from '@pages/home';
import TestPage from '@pages/test';
import UseStateTestPage from '@pages/test/useStateTest';
import UseCallbackTestPage from '@pages/test/useCallbackTest';
import UseMemoTestPage from '@pages/test/useMemoTest';
import UseRefTestPage from '@pages/test/useRefTest';
import ChildTestPage from '@pages/test/childTest';
import TaskPage from '@pages/task';
import SchedulePage from '@pages/task/schedule';
import ResultPage from '@pages/task/result';
import React, { useMemo } from "react";

// 定义菜单项类型
type MenuItem = {
  key: string;
  icon?: React.ReactNode;
  label: React.ReactNode;
  path?: string;
  redirect?: string;
  element?: React.ReactNode;
  children?: MenuItem[];
};

// 定义菜单项列表
const menuItems: MenuItem[] = [
  {
    key: 'home',
    icon: <HomeOutlined />,
    label: '主页',
    path: '/',
    element: <HomePage />
  },
  {
    key: 'task',
    icon: <CalendarOutlined />,
    label: '任务管理',
    path: '/task',
    redirect: '/task/schedule',
    element: <TaskPage />,
    children: [
      {
        key: 'schedule',
        label: '任务计划',
        path: '/task/schedule',
        element: <SchedulePage />
      },
      {
        key: 'result',
        label: '执行结果',
        path: '/task/result',
        element: <ResultPage />
      }
    ]
  },
  {
    key: 'test',
    icon: <ToolOutlined />,
    label: '测试',
    path: '/test',
    redirect: '/test/useStateTest',
    element: <TestPage />,
    children: [
      {
        key: 'useStateTest',
        label: 'useState测试',
        path: '/test/useStateTest',
        element: <UseStateTestPage />
      },
      {
        key: 'useCallbackTest',
        label: 'useCallback测试',
        path: '/test/useCallbackTest',
        element: <UseCallbackTestPage />
      },
      {
        key: 'useMemoTest',
        label: 'useMemo测试',
        path: '/test/useMemoTest',
        element: <UseMemoTestPage />
      },
      {
        key: 'useRefTest',
        label: 'useRef测试',
        path: '/test/useRefTest',
        element: <UseRefTestPage />
      },
      {
        key: 'childTest',
        label: 'Child测试',
        path: '/test/childTest',
        element: <ChildTestPage />
      }
    ]
  }
];

// 从菜单项生成路由配置
const generateRoutes = (items: MenuItem[]): Array<{key: string, path: string, element: React.ReactNode}> => {
  let routes: Array<{key: string, path: string, element: React.ReactNode}> = [];
  
  items.forEach(item => {
    if (item.path && item.element) {
      routes.push({
        key: item.key,
        path: item.path,
        element: item.element
      });
    }
    
    if (item.children) {
      routes = routes.concat(generateRoutes(item.children));
    }
  });
  
  return routes;
};

// 侧边菜单组件
export const SideMenu: React.FC<{ currentPath: string; onNavigate: (path: string) => void }> = ({ 
  currentPath, 
  onNavigate 
}) => {
  // 确定选中的菜单项
  const [selectedKey, setSelectedKey] = useState('');
  
  useEffect(() => {
    // 根据当前路径查找匹配的菜单项
    const findMatchingItem = (items: MenuItem[]): string | undefined => {
      for (const item of items) {
        if (item.path && currentPath === item.path) {
          return item.key;
        }
        
        if (item.redirect && currentPath === item.redirect) {
          return item.key;
        }
        
        if (item.children) {
          const childKey = findMatchingItem(item.children);
          if (childKey) {
            return childKey;
          }
        }
      }
      
      return undefined;
    };
    
    const matchingKey = findMatchingItem(menuItems);
    if (matchingKey) {
      setSelectedKey(matchingKey);
    } else if (currentPath.startsWith('/test')) {
      // 对于测试相关的路径，默认选中test菜单项
      setSelectedKey('test');
    } else if (currentPath.startsWith('/task')) {
      // 对于任务相关的路径，默认选中task菜单项
      setSelectedKey('task');
    } else {
      // 默认选中主页
      setSelectedKey('home');
    }
  }, [currentPath]);
  
  // 处理菜单点击事件
  const handleClick = ({ key }: { key: string }) => {
    // 查找被点击的菜单项
    const findItem = (items: MenuItem[]): MenuItem | undefined => {
      for (const item of items) {
        if (item.key === key) {
          return item;
        }
        
        if (item.children) {
          const found = findItem(item.children);
          if (found) {
            return found;
          }
        }
      }
      
      return undefined;
    };
    
    const item = findItem(menuItems);
    
    if (item) {
      // 优先使用 redirect，其次使用 path
      const targetPath = item.redirect || item.path;
      if (targetPath) {
        onNavigate(targetPath);
      }
    }
  };
  
  // 将菜单项转换为Ant Design Menu组件所需的格式
  const convertToMenuItems = (items: MenuItem[]): MenuProps['items'] => {
    return items.map(item => {
      if (item.children) {
        return {
          key: item.key,
          icon: item.icon,
          label: item.label,
          children: convertToMenuItems(item.children)
        };
      }
      
      return {
        key: item.key,
        icon: item.icon,
        label: item.label
      };
    });
  };
  
  return (
    <Menu
      theme="dark"
      mode="inline"
      selectedKeys={[selectedKey]}
      onClick={handleClick}
      items={convertToMenuItems(menuItems)}
    />
  );
};

// 导出页面容器组件
export const PageContainer = () => {
  const routes = useMemo(() => generateRoutes(menuItems), []);
  
  return (
    <Routes>
      {routes.map(item => (
        <Route key={item.key} path={item.path} element={item.element} />
      ))}
    </Routes>
  );
};